define(['zepto', 'underscore', '../com.52zzb.common/ajax', 'butterflysoc/components/socview', 'butterflysoc/components/store', 'butterflysoc/components/loader',
        'iscroll', '../com.52zzb.common/ajax', '../com.52zzb.common/config', 'text!com.52zzb.main/main.html',
        'butterflysoc/components/dialog', '../com.52zzb.common/toast', '../com.52zzb.common/swipe', 'photoswipe', 'photoswipe_ui_default', 'async'
    ],
    function($, _, na, SocView, Store, Loader, iScroll, AjaxPlugin, Config, example, Dialog, Toast, Swipe, PhotoSwipe, PhotoSwipeUI_Default, Async) {

        var bubble = true; //手动阻止冒泡

        var album_array_new = []; //
        var isload_end = false;

        Store.saveObject('index_is_refresh', true); //判断是否刷新首页

        var View = SocView.extend({
            id: "main-module-main",
            me: null,
            events: {
                "click #main-module-main .head_pic": "gousercenter",
                "click #main-module-main .zhan": "fnZhanPlus",
                "click #main-module-main .comment": "fnCommentPlus",
                "click #main-module-main .news_li": "fnDetail_go",
                "click .fixed_fatie": "shareDemo", //
                "click #main-module-main #gogo_list": "fnGOgoList_go",
                "click #main-module-main .gogo-li": "fnGogo_go",
                "click #main-module-main .gogo-share": "fnShareDetail_go",
                "click #main-module-main #to_gogo_list": "fnonegogolist"

            },
            render: function() {
                $(this.el).html(example);
                SocView.prototype.render.call(this);
                return this;
            },
            fnCommentPlus: function(e) {
                var me = this;
                bubble = false;
                console.log('评论添加');
                // Store.saveObject('isShowKeybord', true);
                var target = e.target;
                while (!$(target).attr('wrapkey')) target = target.parentNode;
                var key = $(target).attr('wrapkey');
                window.butterfly.navigate('com.52zzb.main/example_detail?id=' + key + '', {
                    trigger: true
                });
            },
            getImgNum: function() {
                // Loader.hide();
                if (window.isDesktop !== true) {
                    album_array_new = [];

                    var album_array = Store.loadObject('albumList');

                    if (album_array instanceof Array === false) {
                        console.log('async.each数组为空');
                        return;
                    } //判断参数是否 为空
                    Async.each(album_array,
                        function(item, callback) {

                            console.log(item.album_path);

                            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {

                                console.log("onFileSystemSuccess");
                                console.log(device.platform);
                                if (device.platform == "iOS") {


                                } else if (device.platform == "Android" || device.platform == "iOS") {

                                    fileSystem.root.getDirectory(item.album_path, {
                                        create: false,
                                        exclusive: false
                                    }, function(dirEntry) {
                                        console.log("onDirectorySystemSuccess");
                                        //console.log(dirEntry);
                                        console.log("----------------------dirEntry.filesystem----------------------------------" + dirEntry.filesystem);
                                        console.log(dirEntry.fullPath);
                                        console.log("---------dirEntry.isDirectory------:" + dirEntry.isDirectory);
                                        console.log(dirEntry.isFile);
                                        console.log(dirEntry.name);

                                        fullPath = dirEntry.fullPath;
                                        // Get a directory reader
                                        var directoryReader = dirEntry.createReader();

                                        // Get a list of all the entries in the directory
                                        directoryReader.readEntries(function(entries) {


                                            var entries_name_list = [];

                                            console.log('====== length: ===== ' + entries.length);
                                            for (var i = 0, len = entries.length; i < len; i++) {

                                                var img_entries_name = entries[i].name;

                                                var img_name = img_entries_name.split(".");

                                                var img_name_len = img_name.length;

                                                if (img_name[img_name_len - 1] == 'jpg' || img_name[img_name_len - 1] == 'png' || img_name[img_name_len - 1] == 'jpeg') {
                                                    // entries.splice(i, 1);
                                                    entries_name_list.push(img_entries_name);
                                                }

                                            }
                                            var entries_name_list_len = entries_name_list.length;

                                            if (entries_name_list_len != 0) {
                                                var example_album_src = cordova.file.externalRootDirectory + item.album_path + entries_name_list[entries_name_list_len - 1];

                                                item.images_total = entries_name_list_len;

                                                item.display_img = example_album_src;

                                                album_array_new.push(item);

                                                // alert(data.filename);

                                                // alert('cacha:   ' + cordova.file.cacheDirectory);

                                                Store.deleteObject('albumList');

                                                // alert(example_album_src);

                                                Store.saveObject('albumList', album_array_new);
                                            }

                                        }, function(error) {
                                            console.log("onDirectorySystemFail");
                                            console.log(error.code);
                                        });
                                    }, function(error) {
                                        console.log("onDirectorySystemFail");
                                        console.log(error.code);
                                    });

                                }

                                console.log(fileSystem);

                            }, function(error) {
                                console.log("onFileSystemFail");
                                console.log(error.code);
                            });

                            callback(null); // must call once  

                        },
                        function(err) {

                            if (err) {
                                console.error("error");
                            }

                        });
                    // }
                }
            },
            onShow: function() {

                if (!window.isDesktop && device.platform == "iOS") {
                    $('.pswp__button--download').remove();
                }

                me = this;

                Page_example = this;

                $('.pswp__button--delete').hide();

                $('.pswp__button--download').show();

                document.removeEventListener("backbutton", onBackKey, false); // 注销返回键 
                document.addEventListener("backbutton", onDoubleKey, false); //返回键
                $("#bottom_control").show();
                $(".main_nav_active").removeClass('main_nav_active');
                $("#home").addClass('main_nav_active');

                if (Store.loadObject('user')) {
                    var user = Store.loadObject('user');
                    var uuid = user.uuid;
                    var token = user.token;
                    var deviceId = user.deviceId;
                    var sessionId = user.sessionId;
                } else {
                    var uuid = '';
                    var token = '';
                    var deviceId = '';
                    var sessionId = '';
                }

                setTimeout(function() {
                    if (!isload_end) {
                        $("#main-module-main .bounce1").remove();
                        $("#main-module-main .loader_display_span").text('加载失败了');
                    }
                }, 5000);

                me.getImgNum();


                var mainList = me.component('examplefeedList');
                if (!mainList) {
                    return;
                }

                var url = Config.server + Config.main_list;
                var html = '';

                mainList.config.url = url;
                mainList.setRequestParams({
                    'id': '',
                    'uuid': uuid,
                    'token': token,
                    'deviceId': deviceId,
                    'sessionId': sessionId
                });
                mainList.loaderText = "Loading...";

                mainList.bind("drawed", function() {
                    $("#main-module-main #loader_display").remove();
                    isload_end = true;
                    console.log('drawed');
                    var iNowPage = mainList.config.page;
                    if (iNowPage == 1) {
                        if ($('#main-module-main .addWrap').length) {
                            $('#main-module-main .addWrap').remove();
                        }

                        var imageArray = ['../tmp/files/top01.jpg', '../tmp/files/top01.jpg', '../tmp/files/top01.jpg'];
                        var data = {};
                        data.imageArray = imageArray;
                        /* 加入轮播开始 */
                        var tp1 = $('#main-module-main #top_lunbo').html();
                        var lunboHtml = _.template(tp1, data);
                        $('#main-module-main .item-content').prepend(lunboHtml);
                        /* 加入轮播结束 */
                        /* 图片轮播js开始 */
                        var bullets = $('#main-module-main #position>li');
                        var banner = new Swipe(me.el.querySelector('#main-module-main #mySwipe'), {
                            continuous: true,
                            // auto: 1000,
                            disableScroll: false,
                            callback: function(pos) {
                                var i = bullets.length;
                                while (i--) {
                                    bullets[i].className = ' ';
                                }
                                bullets[pos].className = 'cur';
                            }
                        });

                        var homeurl = Config.server + Config.main_home;
                        var gogoHtml = '';

                        var gogotitle = '<h2 class="h2-title" id="to_gogo_list">美图展示<strong style="font-size:12px;color: #777676">     &nbsp;&nbsp; 啦啦啦啦啦啦啦啦</strong><span></span></h2>';

                        var exampletitle = '<h2 class="h2-title" id="seperate">图文列表<strong style="font-size:12px;color: #777676">      &nbsp;&nbsp;喔喔哦喔喔哦哦哦哦哦</strong></h2>';
                        $.ajax({
                            url: homeurl,
                            data: {},
                            type: 'post',
                            dataType: 'json',
                            success: function(data) {
                                data.expath = Config.picserver; //图片服务器地址
                                data.imagew300jpg = Config.imagew300jpg; //七牛后缀 设置宽度最大300px
                                data.imagew200_100jpg = Config.imagew200_100jpg;
                                if (data.code == 10000) {
                                    var list1 = data.list1;
                                    var list3 = data.list3;
                                    gogoHtml = '<ul class="index-mall clear">';
                                    for (var i = 0, len = list1.length; i < len; i++) {
                                        gogoHtml += '<li class="gogo-li" goid="' + list1[i].id + '"><img src="' + Config.picserver + list1[i].coverPath + Config.imagew300jpg + '" />' + '<p>剩余<span style="color:rgba(255, 105, 6, 0.8);">' + list1[i].remainingTotal + '</span>份</p></li>';
                                    }
                                    gogoHtml += '</ul>';

                                    $('#main-module-main .h2-title').remove();
                                    $('#main-module-main .index-mall').remove();
                                    $('#main-module-main #position').after(exampletitle);

                                    $('#main-module-main #position').after(gogoHtml);
                                    $('#main-module-main #position').after(gogotitle);

                                    mainList.iScroll.refresh();

                                    //广告图链接
                                    $(".img-responsive").eq(0).click(function() {
                                        window.butterfly.navigate('com.52zzb.main/index', {
                                            trigger: true
                                        });
                                    });
                                    $(".img-responsive").eq(1).click(function() {
                                        window.butterfly.navigate('com.52zzb.main/index', {
                                            trigger: true
                                        });
                                        $("#bottom_control").show();
                                        $(".main_nav_active").removeClass('main_nav_active');
                                        $("#found").addClass('main_nav_active');
                                    });
                                }
                            }
                        });
                    };

                    if (Store.loadObject('addexample')) { //判断是否有新信息发布
                        mainList.iScroll.scrollTo(0, -500, 100, false);
                        Store.deleteObject('addexample');
                    }
                    me.initPhotoSwipeFromDOM('#main-module-main .img_list');
                   
                });
            },
            //photoSwipe 函数
            initPhotoSwipeFromDOM: function(gallerySelector) {
                // parse slide data (url, title, size ...) from DOM elements 
                // (children of gallerySelector)
                function parseThumbnailElements(el) {

                    var thumbElements = el.childNodes,
                        numNodes = thumbElements.length,
                        items = [],
                        figureEl,
                        childElements,
                        linkEl,
                        size,
                        item;

                    for (var i = 0; i < numNodes; i++) {

                        figureEl = thumbElements[i]; // <figure> element

                        // include only element nodes 

                        if (figureEl.nodeType !== 1) {

                            continue;

                        }

                        linkEl = figureEl.children[0]; // <a> element

                        size = linkEl.getAttribute('data-size').split('x');
                        // size=[1024,1024];

                        // create slide object
                        item = {
                            src: linkEl.getAttribute('href'),
                            w: parseInt(size[0], 10),
                            h: parseInt(size[1], 10)
                        };



                        if (figureEl.children.length > 1) {
                            // <figcaption> content
                            item.title = figureEl.children[1].innerHTML;
                        }

                        if (linkEl.children.length > 0) {
                            // <img> thumbnail element, retrieving thumbnail url
                            item.msrc = linkEl.children[0].getAttribute('src');
                        }

                        item.el = figureEl; // save link to element for getThumbBoundsFn
                        items.push(item);
                    }

                    return items;
                };

                // find nearest parent element
                var closest = function closest(el, fn) {
                    return el && (fn(el) ? el : closest(el.parentNode, fn));
                };

                // triggers when user clicks on thumbnail
                function onThumbnailsClick(e) {
                    console.log('onThumbnailsClick');
                    bubble = false;
                    e = e || window.event;
                    e.preventDefault ? e.preventDefault() : e.returnValue = false;

                    var eTarget = e.target || e.srcElement;

                    var clickedListItem = closest(eTarget, function(el) {
                        return el.tagName === 'FIGURE';
                    });

                    if (!clickedListItem) {
                        return;
                    }

                    // find index of clicked item
                    var clickedGallery = clickedListItem.parentNode,
                        childNodes = clickedListItem.parentNode.childNodes,
                        numChildNodes = childNodes.length,
                        nodeIndex = 0,
                        index;

                    for (var i = 0; i < numChildNodes; i++) {
                        if (childNodes[i].nodeType !== 1) {
                            continue;
                        }

                        if (childNodes[i] === clickedListItem) {
                            index = nodeIndex;
                            break;
                        }
                        nodeIndex++;
                    }

                    if (index >= 0) {
                        openPhotoSwipe(index, clickedGallery);
                    }
                    return false;
                };

                // parse picture index and gallery index from URL (#&pid=1&gid=2)
                function photoswipeParseHash() {
                    var hash = window.location.hash.substring(1),
                        params = {};

                    if (hash.length < 5) {
                        // if (true) {
                        return params;
                    }

                    var vars = hash.split('&');
                    for (var i = 0; i < vars.length; i++) {
                        if (!vars[i]) {
                            continue;
                        }
                        var pair = vars[i].split('=');
                        if (pair.length < 2) {
                            continue;
                        }
                        params[pair[0]] = pair[1];
                    }

                    if (params.gid) {
                        params.gid = parseInt(params.gid, 10);
                    }

                    if (!params.hasOwnProperty('pid')) {
                        return params;
                    }
                    params.pid = parseInt(params.pid, 10);
                    return params;
                };

                function openPhotoSwipe(index, galleryElement, disableAnimation) {
                    console.log('openPhotoSwipe');

                    document.removeEventListener("backbutton", onDoubleKey, false);
                    document.addEventListener("backbutton", onBackKey, false); // 注销返回键 

                    var pswpElement = document.querySelectorAll('.pswp')[0],
                        gallery,
                        options,
                        items;

                    items = parseThumbnailElements(galleryElement);

                    // define options (if needed)
                    options = {
                        index: index,

                        // define gallery index (for URL)
                        galleryUID: galleryElement.getAttribute('data-pswp-uid'),

                        getThumbBoundsFn: function(index) {
                            // See Options -> getThumbBoundsFn section of docs for more info
                            var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                                pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                                rect = thumbnail.getBoundingClientRect();

                            return {
                                x: rect.left,
                                y: rect.top + pageYScroll,
                                w: rect.width
                            };
                        },

                        // history & focus options are disabled on CodePen
                        // remove these lines in real life: 
                        historyEnabled: false,
                        focus: true

                    };

                    if (disableAnimation) {
                        options.showAnimationDuration = 0;
                    }

                    // Pass data to PhotoSwipe and initialize it
                    gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
                    gallery.init();
                    // gallery.updateSize(false);

                    //监听photoSwipe关闭
                    gallery.listen('close', function() {
                        console.log('my_photo_swipe_close');
                        document.removeEventListener("backbutton", onBackKey, false); // 注销返回键 
                        document.addEventListener("backbutton", onDoubleKey, false);
                    });
                    console.log('gallery.currItem.length ' + gallery.items.length);
                    if (gallery.items.length == 1) {
                        $('.pswp__counter').css('opacity', '0');
                    } else {
                        $('.pswp__counter').css('opacity', '1');
                    }
                };

                // loop through all gallery elements and bind events
                var galleryElements = document.querySelectorAll(gallerySelector);

                for (var i = 0, l = galleryElements.length; i < l; i++) {
                    galleryElements[i].setAttribute('data-pswp-uid', i + 1);
                    galleryElements[i].onclick = onThumbnailsClick;
                }

                // Parse URL and open gallery if it contains #&pid=3&gid=1
                var hashData = photoswipeParseHash();
                if (hashData.pid > 0 && hashData.gid > 0) {
                    openPhotoSwipe(hashData.pid - 1, galleryElements[hashData.gid - 1], true);
                }
            },
            swipedemo_go: function() {
                window.butterfly.navigate('com.52zzb.main/swipedemo', {
                    trigger: true
                });
            },
            gousercenter: function(e) {
                bubble = false;
                var target = e.target;
                var data = $(target).attr('id');
                // Store.saveObject('userId', data);
                window.butterfly.navigate('com.52zzb.main/usercenter?id=' + data + '', {
                    trigger: true
                });

            },
            fnDetail_go: function(e) {
                if (bubble) {
                    var target = e.target;
                    while (!$(target).attr('wrapkey')) target = target.parentNode;
                    var key = $(target).attr('wrapkey');
                    // Store.saveObject('GoodsDetailId', key);


                    window.butterfly.navigate('com.52zzb.main/example_detail?id=' + key + '', {
                        trigger: true
                    });
                } else {
                    bubble = true;
                }
            },
            fnZhanPlus: function(e) {
                var me = this;
                bubble = false;
                var target = e.target;
                while (!$(target).attr('key')) target = target.parentNode;
                var userId = $(target).attr('key');
                if (Store.loadObject('user')) {
                    var user = Store.loadObject('user');
                    var uuid = user.uuid;
                    var token = user.token;
                    var deviceId = user.deviceId;
                    var sessionId = user.sessionId;
                } else {
                    var uuid = '';
                    var token = '';
                    var deviceId = '';
                    var sessionId = '';
                }
                if ($('#main-module-main #zhan' + userId + ' img').attr('src') == '../com.52zzb.common/images/zhan1.png') {
                    $('#main-module-main #zhan' + userId + ' img').addClass('zhan_css3');
                    $('#main-module-main #zhan' + userId + ' img').attr('src', '../com.52zzb.common/images/zhan3.png');
                    var num = $('#main-module-main #zhan' + userId + ' span').text();
                    $.ajax({
                        url: Config.server + Config.example_support,
                        data: {
                            'id': userId,
                            'uuid': uuid,
                            'token': token,
                            'deviceId': deviceId,
                            'sessionId': sessionId
                        },
                        type: 'post',
                        dataType: 'json',
                        success: function(data) {
                            setTimeout(function() {

                                $('#main-module-main #zhan' + userId + ' img').removeClass('zhan_css3');

                            }, 500);

                            if (data.code == 10000) {
                                num++;
                                $('#main-module-main #zhan' + userId + ' img').attr('src', '../com.52zzb.common/images/zhan2.png');
                                $('#main-module-main #zhan' + userId + ' span').text(num);
                            } else if (data.code == -10002) {
                                Toast(data.msg);
                                $('#main-module-main #zhan' + userId + ' img').attr('src', '../com.52zzb.common/images/zhan1.png');
                            } else if (data.code == -10001) {
                                me.showdialog(data.msg);
                                $('#main-module-main #zhan' + userId + ' img').attr('src', '../com.52zzb.common/images/zhan1.png');
                            }
                        }
                    });
                } else {
                    Toast('亲~已经攒过了');
                }
            },
            fnPublishPage_go: function() {

                // if (go_publish) {
                // if (Store.loadObject('albumList')) {
                if (Store.loadObject('user')) {
                    var user = Store.loadObject('user');
                    var uuid = user.uuid;
                    var token = user.token;
                    var deviceId = user.deviceId;
                    var sessionId = user.sessionId;
                    console.log(sessionId);
                    $.ajax({
                        url: Config.server + Config.user_check_login,
                        data: {
                            'uuid': uuid,
                            'token': token,
                            'deviceId': deviceId,
                            'sessionId': sessionId
                        },
                        type: 'post',
                        dataType: 'json',
                        success: function(data) {
                            if (data.code == 10000) {
                                window.butterfly.navigate('com.52zzb.main/publish_page', {
                                    trigger: true
                                });

                            } else if (data.code == 10001) {
                                window.butterfly.navigate('com.52zzb.main/perfect_inf', {
                                    trigger: true
                                });
                            } else if (data.code == -10001) {
                                Store.saveObject('href', window.location.href);
                                window.butterfly.navigate('com.52zzb.main/login', {
                                    trigger: true
                                });
                            } else {
                                Toast(data.msg);
                            }
                        }
                    });
                } else {
                    Store.saveObject('href', window.location.href);
                    window.butterfly.navigate('com.52zzb.main/login', {
                        trigger: true
                    });
                }


            },
            shareDemo: function() {


                bubble = false;
                // alert("ff");
                WeChat.share({
                    scene: WeChat.Scene.timeline,
                    type: WeChat.ShareType.webpage,
                    title: '链接',
                    description: '链接描述',
                    url: 'http://www.infinitus.com.cn/'
                }, WeChat.Scene.timeline, function() {
                    console.log('分享成功~');
                }, function() {
                    //alert(reason);
                    //console.log(reason);
                });

                return;

                dialog = new Dialog({
                    autoshow: false,
                    target: 'body',
                    title: '<p style="text-align:left;text-indent:1em;color:#333">分享到：</p>',
                    content: '<ul class="share_wrap clear"><li><img src="../com.52zzb.common/images/weixin.png"/><p>微信好友</p></li><li><img src="../com.52zzb.common/images/share_qq.png"/><p>qq好友</p></li><li><img src="../com.52zzb.common/images/share_weibo.png"/><p>微博</p></li></ul>'
                }, {
                    configs: [{
                        title: '取消',
                        eventName: 'cancle',
                    }],
                    cancle: function() {

                    }
                });
                dialog.show();
                window.plugins.socialsharing.shareVia('com.tencent.mobileqq', '来自E帆网', null, null, 'http://www.53vm.com/', function() {
                    console.log('share ok')
                }, function(errormsg) {
                    alert(errormsg)
                })
            },
            fnGOgoList_go: function() {
                window.butterfly.navigate('com.52zzb.main/onegogolist', {
                    trigger: true
                });
            },
            fnGogo_go: function(e) {

                // Store.saveObject('index_is_refresh', true);
                var target = e.target;
                while (!$(target).attr('goid')) target = target.parentNode;
                Store.saveObject('go_id', $(target).attr('goid'));
                window.butterfly.navigate('com.52zzb.main/onegogo', {
                    trigger: true
                });
            },
            fnShareList_go: function() {
                window.butterfly.navigate('com.52zzb.main/share_order', {
                    trigger: true
                });
            },
            fnonegogolist: function() {
                window.butterfly.navigate('com.52zzb.main/onegogolist', {
                    trigger: true
                });
            },
            downLoadImg: function(downUrl) {
                if (device.platform == "Android") {
                    var fileURL = cordova.file.externalRootDirectory + 'Pictures/daxuelian/' + downUrl.substr(downUrl.lastIndexOf('/') + 1);
                    var fileTransfer = new FileTransfer();
                    var uri = encodeURI(downUrl);
                    fileTransfer.download(
                        uri,
                        fileURL,
                        function(entry) {
                            console.log("download complete: " + entry.toURL());
                        },
                        function(error) {
                            console.log("download error source " + error.source);
                            console.log("download error target " + error.target);
                            console.log("upload error code" + error.code);
                        },
                        false, {
                            headers: {
                                'headerParam': 'headerValue'
                            }
                        }
                    );
                }

            }
        });
        return View;
    });
